package com.example.demo.exception;

import com.example.demo.error.Result;
import com.example.demo.error.ResultGenerator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author admin
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException ex) {
        ex.printStackTrace();
        return ResultGenerator.getErrorResult(ex.getMessage());
//        return ResponseEntity
//                .status(HttpStatus.BAD_REQUEST)
//                .body(ApiResponse.error(ex.getCode(), ex.getMessage()));
    }

    // 处理其他未捕获的异常
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception ex) {
        ex.printStackTrace(); // 打印堆栈信息（仅用于调试）
        return ResultGenerator.getErrorResult("服务内部错误，请联系管理人员");
//        return ResponseEntity
//                .status(HttpStatus.INTERNAL_SERVER_ERROR)
//                .body(ApiResponse.error(500, "服务器内部错误"));
    }

    // 处理特定异常（如 SQL 异常）
//    @ExceptionHandler(org.springframework.dao.DataIntegrityViolationException.class)
//    public Result<?> handleDataIntegrityViolationException(Exception ex) {
//        return ResultGenerator.getErrorResult()
//        return ResponseEntity
//                .status(HttpStatus.BAD_REQUEST)
//                .body(ApiResponse.error(400, "数据完整性错误：" + ex.getMessage()));
//    }
}
